#include <iostream>
#include <memory>
#include "tcp_client.hpp"

using namespace std;
using namespace ns_client;

ns_protocol::Request func(const string& msg)
{
    // 将结果存入 字符串数组 中，然后转化
    std::vector<std::string> result(3);

    enum
    {
        X,
        OP,
        Y
    };

    int flag = X; // 默认先读 _x

    int pos = 0;
    while (pos < msg.size())
    {
        switch (flag)
        {
        case X:
            if (isdigit(msg[pos]))
                result[flag].push_back(msg[pos++]);
            else
                flag = OP;
            break;
        case OP:
            result[flag].push_back(msg[pos++]);
            flag = Y;
            break;
        case Y:
            result[flag].push_back(msg[pos++]);
            break;
        default:
            logMessage(Warning, "表达式非法");
            break;
        }
    }

    int x = Util::StrToInt(result[0]);
    char op = result[1][0];
    int y = Util::StrToInt(result[2]);

    return ns_protocol::Request(x, op, y);
}

void Usage(const char *porc)
{
    cout << "Usage:" << endl;
    cout << "\t" << porc << " ServerIP ServerPort" << endl;
}

int main(int argc, char *argv[])
{
    std::string ip;
    uint16_t port;

    if (argc != 3)
    {
        cout << "参数传递有误，已按默认设定进行连接" << endl;
        Usage(argv[0]);
        ip = default_ip;
        port = default_port;
    }
    else
    {
        ip = string(argv[1]);
        port = stoi(argv[2]);
    }
    unique_ptr<TcpClient> tcit(new TcpClient(func, ip, port));

    tcit->InitClient();
    tcit->StartClient();

    return 0;
}
